<?php

/*
 *------------------------------------------------------------------------------
 * Project Name  : e-Synergy Library System
 *         Code  : ESN-LBS
 *
 * Created By    : Junlapong
 *         Date  : 2010/01/21
 *
 * $Id$
 *------------------------------------------------------------------------------
 *    copyright: e-Synergy Co., Ltd.
 *==============================================================================
 */

class Login extends MY_Controller
{
    function Login()
    {    	
		define('LOGIN_PAGE', 'login_page');
		
        parent::MY_Controller();
        
        $this->load->model('login_model', 'model');
        $this->load->entity(array('user_entity'));
    }

    function index()
    {    	
	    $data['input']         = $this->_get_input();
	    $data['error_message'] = '';
    	
    	$this->load->view('login_view', $data);
    }

    /**
     * verify username and password
     * 
     */
    function authenticate()
    {   
    	// 1. get input data 	
    	$input = $this->_get_input();
    	
    	$username = $input['username'];
    	$password = $input['password'];    	

    	$verify = FALSE;
    	    			
    	// 2. check
    	if (! is_empty($input['username']) && ! is_empty($input['password']))
    	{
    		$user = $this->model->getUser($username);
    		   		
    		// check user data
    		if ($user != NULL)
    		{    			
    			// check authentication mode
    			if (AUTHEN_MODE_DB == $user->authen_mode)
    			{
    				if (sha1($password) === $user->password)
    				{
    					$verify = TRUE;
    				}
    			}
    			elseif (AUTHEN_MODE_LDAP == $user->authen_mode)
    			{
    				// TODO implements ldap method
    			}
    		}    			
    	}

    	// OK
    	if ($verify === TRUE)
    	{
    		$this->session->set('login_status', LOGIN_STATUS_ONLINE);
    		$this->session->set('user_data', $user);
    		
    		redirect(site_url());
    	}
    
    	// error
    	else
    	{
    		$data['error_message'] = lang('login_password_incorrect'); 
    		$data['input'] = $input;
    		
    		$this->load->view('login_view', $data);     			
    	} 
    }

    /**
     * logout
     * 
     */
    function logout()
    {
		$this->session->invalidate();

		redirect(site_url('login'), 'refresh');
    }
    
    
    //---------- private method -----------------------------------------------
    
    function _get_input()
    {
    	$input = array();
    	
    	$input['username'] = $this->input->post('username');
    	$input['password'] = $this->input->post('password');
    	$input['remember_pass'] = $this->input->post('remember_pass') == 'on' ? 'checked="checked"' : '';
    	
    	return $input;
    }
}

// END Login class

/* End of file Login */
/* Location: application/controllers/login.php */